import React from "react"
import * as ReactDOM from 'react-dom'
import {Modal} from '@/components'
import Icon from "@/components/Icon/Icon";


class ModalExtensions {
	storeKeyIndex = 0
	containers = {}

	handleCancel(props, storeKeyIndex, event) {
		const {
			onCancel
		} = props
		onCancel && onCancel(event)
	}

	handleClose(props, storeKeyIndex) {
		const container = this.containers[storeKeyIndex]
		ReactDOM.unmountComponentAtNode(container)
		document.body.removeChild(container);
	}

	handelOk(props, storeKeyIndex, event) {
		const {
			onOk
		} = props
		return onOk && onOk(event)
	}

	createContainer(storeKeyIndex) {
		const container = document.createElement('div');
		document.body.appendChild(container)
		this.containers[storeKeyIndex] = container
		return container
	}

	alert(content, props = {}) {
		this.storeKeyIndex++
		const {
			title,
			width,
			height,
			left,
			top,
			icon,
			className
		} = (props || {})
		ReactDOM.render(
			<Modal name={this.getStoreKey(this.storeKeyIndex)}
				   renderInBody={false}
				   active={true}
				   left={left}
				   top={top}
				   width={width || 400}
				   height={height}
				   className={className || 'modal-alert'}
				   showCancel={false}
				   onOk={this.handelOk.bind(this, props, this.storeKeyIndex)}
				   onClose={this.handleClose.bind(this, props, this.storeKeyIndex)}>
				{title ? <div slot='header'>{icon ? <Icon type={icon}/> : null}{title}</div> : null}
				{content}
			</Modal>, this.createContainer(this.storeKeyIndex))
	}

	info(content, props) {
		this.alert(content, {
			icon: 'info',
			title: '提示',
			className: 'modal-info',
			...props
		})
	}

	warn(content, props) {
		this.alert(content, {icon: 'warn', title: '警告', className: 'modal-warn', ...props})
	}

	error(content, props) {
		this.alert(content, {icon: 'error', title: '错误', className: 'modal-error', ...props})
	}

	success(content, props) {
		this.alert(content, {icon: 'success', title: '成功', className: 'modal-success', ...props})
	}

	getStoreKey(index) {
		return `modalExt${index}`
	}

	confirm(props) {
		this.storeKeyIndex++
		const {
			title,
			content,
			width,
			height,
			left,
			top
		} = props

		ReactDOM.render(
			<Modal name={this.getStoreKey(this.storeKeyIndex)}
				   renderInBody={false}
				   active={true}
				   left={left}
				   top={top}
				   width={width || 400}
				   height={height}
				   className='confirm'
				   onClose={this.handleClose.bind(this, props, this.storeKeyIndex)}
				   onOk={this.handelOk.bind(this, props, this.storeKeyIndex)}
				   onCancel={this.handleCancel.bind(this, props, this.storeKeyIndex)}>
				<div slot='header'>{title}</div>
				{content}
			</Modal>, this.createContainer(this.storeKeyIndex))
	}
}

export default new ModalExtensions()
